import { get, post } from '@/utils/request'
import { ElMessage, ElNotification } from 'element-plus'

// API连接测试工具
export class ApiTestUtil {
  constructor() {
    this.testResults = []
    this.isTestingConnection = false
  }

  // 测试API连接
  async testApiConnection() {
    if (this.isTestingConnection) {
      ElMessage.warning('正在测试连接，请稍候...')
      return
    }

    this.isTestingConnection = true
    this.testResults = []

    try {
      ElNotification({
        title: 'API连接测试',
        message: '开始测试后端API连接...',
        type: 'info',
        duration: 2000
      })

      // 测试基础连接
      await this.testBasicConnection()
      
      // 测试认证接口
      await this.testAuthEndpoints()
      
      // 测试业务接口
      await this.testBusinessEndpoints()

      // 显示测试结果
      this.showTestResults()

    } catch (error) {
      console.error('API连接测试失败:', error)
      ElNotification({
        title: 'API连接测试失败',
        message: error.message || '无法连接到后端服务',
        type: 'error',
        duration: 5000
      })
    } finally {
      this.isTestingConnection = false
    }
  }

  // 测试基础连接
  async testBasicConnection() {
    try {
      const response = await get('/health', {}, { 
        showError: false,
        showLoading: false,
        timeout: 5000
      })
      
      this.addTestResult('基础连接', true, '后端服务正常运行')
      return response
    } catch (error) {
      this.addTestResult('基础连接', false, error.message)
      throw error
    }
  }

  // 测试认证接口
  async testAuthEndpoints() {
    const authTests = [
      {
        name: '登录接口',
        endpoint: '/auth/login',
        method: 'POST',
        data: { username: 'test', password: 'test' }
      },
      {
        name: '验证码接口',
        endpoint: '/auth/verify-code',
        method: 'POST',
        data: { phone: '13800138000' }
      }
    ]

    for (const test of authTests) {
      try {
        if (test.method === 'POST') {
          await post(test.endpoint, test.data, { 
            showError: false,
            showLoading: false,
            timeout: 5000
          })
        } else {
          await get(test.endpoint, {}, { 
            showError: false,
            showLoading: false,
            timeout: 5000
          })
        }
        
        this.addTestResult(test.name, true, '接口可访问')
      } catch (error) {
        // 401错误是正常的，说明接口存在但需要认证
        if (error.response?.status === 401 || error.code === 401) {
          this.addTestResult(test.name, true, '接口存在（需要认证）')
        } else {
          this.addTestResult(test.name, false, error.message)
        }
      }
    }
  }

  // 测试业务接口
  async testBusinessEndpoints() {
    const businessTests = [
      {
        name: '仪表板数据',
        endpoint: '/dashboard/overview',
        method: 'GET'
      },
      {
        name: '订单列表',
        endpoint: '/orders',
        method: 'GET'
      },
      {
        name: '服务列表',
        endpoint: '/services',
        method: 'GET'
      },
      {
        name: '财务概览',
        endpoint: '/finance/overview',
        method: 'GET'
      },
      {
        name: '评价列表',
        endpoint: '/reviews',
        method: 'GET'
      },
      {
        name: '保证金统计',
        endpoint: '/deposit/stats',
        method: 'GET'
      }
    ]

    for (const test of businessTests) {
      try {
        if (test.method === 'POST') {
          await post(test.endpoint, test.data || {}, { 
            showError: false,
            showLoading: false,
            timeout: 5000
          })
        } else {
          await get(test.endpoint, {}, { 
            showError: false,
            showLoading: false,
            timeout: 5000
          })
        }
        
        this.addTestResult(test.name, true, '接口可访问')
      } catch (error) {
        // 401错误是正常的，说明接口存在但需要认证
        if (error.response?.status === 401 || error.code === 401) {
          this.addTestResult(test.name, true, '接口存在（需要认证）')
        } else {
          this.addTestResult(test.name, false, error.message)
        }
      }
    }
  }

  // 添加测试结果
  addTestResult(name, success, message) {
    this.testResults.push({
      name,
      success,
      message,
      timestamp: new Date().toLocaleTimeString()
    })
  }

  // 显示测试结果
  showTestResults() {
    const successCount = this.testResults.filter(r => r.success).length
    const totalCount = this.testResults.length
    const successRate = Math.round((successCount / totalCount) * 100)

    let resultMessage = `测试完成: ${successCount}/${totalCount} 通过 (${successRate}%)\n\n`
    
    this.testResults.forEach(result => {
      const status = result.success ? '✅' : '❌'
      resultMessage += `${status} ${result.name}: ${result.message}\n`
    })

    console.log('API连接测试结果:', this.testResults)

    if (successRate >= 80) {
      ElNotification({
        title: 'API连接测试完成',
        message: `${successCount}/${totalCount} 个接口测试通过`,
        type: 'success',
        duration: 5000
      })
    } else if (successRate >= 50) {
      ElNotification({
        title: 'API连接测试完成',
        message: `${successCount}/${totalCount} 个接口测试通过，部分接口可能需要配置`,
        type: 'warning',
        duration: 5000
      })
    } else {
      ElNotification({
        title: 'API连接测试失败',
        message: `仅 ${successCount}/${totalCount} 个接口测试通过，请检查后端服务`,
        type: 'error',
        duration: 8000
      })
    }
  }

  // 获取测试结果
  getTestResults() {
    return this.testResults
  }

  // 清除测试结果
  clearTestResults() {
    this.testResults = []
  }
}

// 创建全局实例
export const apiTestUtil = new ApiTestUtil()

// 数据库连接状态检查
export async function checkDatabaseConnection() {
  try {
    const response = await get('/system/database/status', {}, {
      showError: false,
      showLoading: false,
      timeout: 5000
    })

    if (response.code === 200) {
      ElNotification({
        title: '数据库连接正常',
        message: `MySQL数据库连接成功\n数据库: ${response.data.database}\n版本: ${response.data.version}`,
        type: 'success',
        duration: 3000
      })
      return true
    } else {
      throw new Error(response.message || '数据库连接失败')
    }
  } catch (error) {
    ElNotification({
      title: '数据库连接失败',
      message: error.message || '无法连接到MySQL数据库',
      type: 'error',
      duration: 5000
    })
    return false
  }
}

// 测试数据初始化
export async function initializeTestData() {
  try {
    ElNotification({
      title: '初始化测试数据',
      message: '正在初始化测试数据...',
      type: 'info',
      duration: 2000
    })

    const response = await post('/system/init-test-data', {}, {
      showLoading: true,
      loadingText: '初始化测试数据中...',
      timeout: 30000
    })

    if (response.code === 200) {
      ElNotification({
        title: '测试数据初始化成功',
        message: '已成功初始化测试数据，可以开始使用系统',
        type: 'success',
        duration: 5000
      })
      return true
    } else {
      throw new Error(response.message || '初始化测试数据失败')
    }
  } catch (error) {
    ElNotification({
      title: '测试数据初始化失败',
      message: error.message || '无法初始化测试数据',
      type: 'error',
      duration: 5000
    })
    return false
  }
}

// 清除测试数据
export async function clearTestData() {
  try {
    const response = await post('/system/clear-test-data', {}, {
      showLoading: true,
      loadingText: '清除测试数据中...',
      timeout: 30000
    })

    if (response.code === 200) {
      ElNotification({
        title: '测试数据清除成功',
        message: '已成功清除所有测试数据',
        type: 'success',
        duration: 3000
      })
      return true
    } else {
      throw new Error(response.message || '清除测试数据失败')
    }
  } catch (error) {
    ElNotification({
      title: '测试数据清除失败',
      message: error.message || '无法清除测试数据',
      type: 'error',
      duration: 5000
    })
    return false
  }
}
